function [icorrected] = traynelis(data, samplerate, Vh, Vr, Rs, Cm, pVcomp, pCm, correction_Fc)
%
% Implementation of correction for series resistance as described by S.F. Traynelis
% in J. Neurosci. Methods, 86: 25-34, 1998.
%
% Paul B. Manis, Ph.D.
% 6/21/02
%
Icap = 0; %#ok<NASGU>
this_v = 0; %#ok<NASGU>
last_v = 0; %#ok<NASGU>
v_correct = 0; %#ok<NASGU>

last_v = (Vh - data(1))*Rs;
if(last_v ~= Vr)
   v_correct = pVcomp * (1 - (Vh - Vr)/(last_v - Vr));
else
   v_correct = 0;
end;
icorrected = zeros(length(data), 1);
icorrected(1) = data(1)-data(1)*v_correct;
for i = 2:length(data)
   this_v = (Vh - data(i))*Rs;
   if(this_v ~= Vr)
      v_correct = pVcomp * (1 - (Vh - Vr)/(this_v - Vr));
   else
      v_correct = 0;
   end;
   Icap = Cm*(this_v-last_v)/samplerate;
   Icap = Icap * (1 - exp(-2*pi*samplerate*correction_Fc));
   icorrected(i-1) = data(i-1)-(pVcomp * Icap);
   icorrected(i-1) = icorrected(i-1)*(1 - v_correct);
   last_v = this_v;
end;
